package me.huanmeng.heater.plugin;

import cn.hutool.core.io.FileUtil;
import com.ericrabil.yamlconfiguration.configuration.file.FileConfiguration;
import com.ericrabil.yamlconfiguration.configuration.file.YamlConfiguration;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 2021/9/29<br>
 * Heater<br>
 *
 * @author huanmeng_qwq
 */
public abstract class JavaBase implements Plugin {
    private File file;
    private File dataFolder;
    private FileConfiguration config;
    private File configFile;
    private ClassLoader classLoader;
    private PluginDescription pluginDescription;
    @Setter
    @Getter
    private boolean enabled;

    @Override
    public @NotNull File getDataFolder() {
        return dataFolder;
    }

    @Override
    public void saveConfig() {
        if (file.exists()) {
            try {
                config.save(configFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public @Nullable FileConfiguration getConfig() {
        return config;
    }

    @Override
    public void saveResource(@NotNull String name, boolean replace) {
        if (name.trim().isEmpty()) {
            return;
        }
        name = name.replace("\\", "/");
        InputStream in = getResource(name);
        if (in == null) {
            throw new IllegalArgumentException(String.format("%s not found.", name));
        }
        File target = new File(dataFolder, name);
        if (!target.exists() || replace) {
            FileUtil.writeFromStream(in, target);
        }
    }

    private InputStream getResource(String name) {
        try {
            final URL url = getClass().getClassLoader().getResource(name);
            if (null == url) {
                return null;
            }
            final URLConnection connection = url.openConnection();
            connection.setUseCaches(false);
            return connection.getInputStream();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void reloadConfig() {
        if (file.exists()) {
            config = YamlConfiguration.loadConfiguration(configFile);
        }
    }

    final void initialize(File file, File dataFolder, PluginDescription pluginDescription, ClassLoader classLoader) {
        this.file = file;
        this.dataFolder = dataFolder;
        this.pluginDescription = pluginDescription;
        this.configFile = new File(dataFolder, "config.yml");
        this.classLoader = classLoader;
    }
    
    @Override
    public PluginDescription getDescription() {
        return pluginDescription;
    }

    final ClassLoader getLoader() {
        return classLoader;
    }
}
